package cn.dankal.basiclib;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.io.File;
import java.util.concurrent.ExecutionException;

import api.ShopUserServiceFactory;
import cn.dankal.basiclib.common.bus.LiveDataBusConstants;
import cn.dankal.basiclib.domain.HttpStatusCode;
import cn.dankal.basiclib.exception.LocalException;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.UserInfoBean;
import cn.dankal.basiclib.pojo.UserResponseBody;
import cn.dankal.basiclib.pojo.UserScoresEntity;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.PreferenceUtil;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * @author vane
 */
public class DKUserManager {

    private static Context mContext = DankalApplication.getContext();
    private static SharedPreferences mSpUserInfo;
    private static SharedPreferences mSpUserScores;
    private static SharedPreferences mSpToken;
    private static final String PreferenceUserInfo = "userinfo";
    private static final String PreferenceToken = "token";
    private static final String PreferenceScores = "scores";
    private static UserInfoBean userInfo;
    private static UserScoresEntity userScores;
    private static UserResponseBody.TokenBean userToken;

    static {
        mSpUserInfo = mContext.getSharedPreferences(PreferenceUserInfo, Context.MODE_PRIVATE);
        mSpToken = mContext.getSharedPreferences(PreferenceToken, Context.MODE_PRIVATE);
        mSpUserScores = mContext.getSharedPreferences(PreferenceScores, Context.MODE_PRIVATE);
    }


    /**
     * 最初mUserInfo各属性内容为空，
     * 如登录后可更新当前的UserInfo和本地的缓存
     */
    public static void saveUserInfo(UserResponseBody userResponseBody) {
        UserInfoBean userInfo = userResponseBody.getUserInfo();
        UserResponseBody.TokenBean token = userResponseBody.getToken();
        if (userInfo != null) {
            PreferenceUtil.updateBean(mSpUserInfo, getUserInfo(), userInfo);
        }
        if (token != null) {
            PreferenceUtil.updateBean(mSpToken, getUserToken(), token);
        }
    }

    public static void updateUserInfoScores(UserScoresEntity userScoresEntity) {
        if (userScoresEntity != null) {
            PreferenceUtil.updateBean(mSpUserScores, getUserScores(), userScoresEntity);
        }
    }

    public static void updateUserInfo(UserInfoBean userInfo) {
        if (userInfo != null) {
            PreferenceUtil.updateBean(mSpUserInfo, getUserInfo(), userInfo);
            updateBaseInfo(userInfo);
            updateJPUSH(userInfo);
        }
    }

    private static void updateBaseInfo(UserInfoBean userInfoBean) {
        UserInfo userInfo = JMessageClient.getMyInfo();
        if (userInfo == null) return;
        userInfo.setNickname(userInfoBean.getName());
        JMessageClient.updateMyInfo(UserInfo.Field.nickname, userInfo, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {

            }
        });
    }

    private static void updateJPUSH(UserInfoBean userInfo) {
        new Thread(() -> {
            try {
                if (!TextUtils.isEmpty(userInfo.getAvatar())) {
                    File mFile = Glide.with(ActivityUtils.getTopActivity()).asFile().load(PicUtils.getUrl(userInfo.getAvatar())).submit().get();
                    JMessageClient.updateUserAvatar(mFile, new BasicCallback() {
                        @Override
                        public void gotResult(int i, String s) {

                        }
                    });
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public static void updateUserToken(UserResponseBody.TokenBean token) {
        if (token != null) {
            PreferenceUtil.updateBean(mSpToken, getUserToken(), token);
        }
    }

    /**
     * 如果从本地缓存中获取对象为空则实例化一个空对象
     * 判断是否登录全程通过user_id是不是为0来判断而不是通过
     * mUserInfo是否等于null，防止UserManager.getUserInfo出现空指针
     */
    private static void readUserInfo() {
        userInfo = (UserInfoBean) PreferenceUtil.getBeanValue(mSpUserInfo, UserInfoBean.class);
        if (userInfo == null) {
            userInfo = new UserInfoBean();
        }
    }

    private static void readUserScores() {
        userScores = (UserScoresEntity) PreferenceUtil.getBeanValue(mSpUserScores, UserScoresEntity.class);
        if (userScores == null) {
            userScores = new UserScoresEntity();
        }
    }

    private static void readUserToken() {
        userToken = (UserResponseBody.TokenBean) PreferenceUtil.getBeanValue(mSpToken,
                UserResponseBody.TokenBean.class);
        if (userToken == null) {
            userToken = new UserResponseBody.TokenBean();
        }
    }

    /**
     * 清空缓存时调用
     */
    public static void resetUserInfo() {
        SharedPreferences.Editor editor = mSpUserInfo.edit();
        editor.clear();
        editor.apply();
        userInfo = new UserInfoBean();
    }

    public static void resetToken() {
        SharedPreferences.Editor editor = mSpToken.edit();
        editor.clear();
        editor.apply();
        userToken = new UserResponseBody.TokenBean();
    }

    /**
     * 判断已经登录
     */
    public static boolean isLogined() {
        return !TextUtils.isEmpty(getUserToken().token);
    }

    public static UserResponseBody.TokenBean getUserToken() {
        if (userToken == null) {
            readUserToken();
        }
        return userToken;
    }

    public static void fetchUserScores() {
        ShopUserServiceFactory.userScores().subscribe(new Observer<BaseResponse<UserScoresEntity>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse<UserScoresEntity> userScoresEntityBaseResponse) {
                DKUserManager.updateUserInfoScores(userScoresEntityBaseResponse.getData());
                LiveEventBus.get(LiveDataBusConstants.REFRESH_USER_SCORES, String.class).post("");
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof LocalException) {
                    LocalException exception = (LocalException) e;
                    //401 重新获取access token , 如果还返回412 就是refresh token 也失效了。需要重新登录
                    if (exception.getErrorCode() == HttpStatusCode.TOKEN_INVAILD ||
                            exception.getErrorCode() == HttpStatusCode.UNAUTHORIZED) {
                        //view.showToast("登录信息失效");
                    } else {
                    }
                } else {
                    Log.e("SubscriberThrowable", e.getMessage());
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    public static UserInfoBean getUserInfo() {
        if (userInfo == null) {
            readUserInfo();
        }
        return userInfo;
    }

    public static UserScoresEntity getUserScores() {
        if (userScores == null) {
            readUserScores();
        }
        return userScores;
    }

}
